<script setup>
import {onMounted, ref, useAttrs, watch} from "vue";

const attrs = useAttrs();

const props = defineProps({
  modelValue: {
    type: [String, Number, Boolean, Array],
    default: ''
  },
  options: {
    type: Array,
    default: () => {
      return [];
    }
  },
  style: {
    type: Object,
    default: () => {
      return {
        width: '100%'
      };
    }
  },
});
const emits = defineEmits(['update:modelValue', 'input', 'change']);
// 绑定数据
const inputValue = ref(props.modelValue);
const inputType = ref('text');
// 监听父组件中传递的数据是否发生变化
watch(() => props.modelValue, (val) => {
  inputValue.value = val;
}, {deep: true});
// 监听当前组件中的输入框数据是否发生变化，变化则需要通知父组件更新数据
watch(() => inputValue.value, (val) => {
  inputValue.value = val;
  handleEmits();
}, {deep: true});

onMounted(() => {
  console.log('attrs', attrs)
  // 如果没有type，则默认为text
  inputType.value = attrs.type || 'text';
});
const handleEmits = (type) => {
  emits('update:modelValue', inputValue.value);
  if (type === 'input') {
    emits('input', inputValue.value);
  } else if (type === 'change') {
    emits('change', inputValue.value);
  }
};
</script>

<template>
  <div style="width: 100%;">
    <el-input v-if="inputType === 'text' || inputType === 'textarea'" v-model="inputValue"
              @input="handleEmits('input')"
              @change="handleEmits('change')"
              v-bind="$attrs" :style="style"/>
    <el-select v-if="inputType === 'select'" v-model="inputValue" :style="style" v-bind="$attrs"
               @change="handleEmits('change')">
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
    </el-select>
    <el-input-number v-if="inputType === 'number'" v-model="inputValue" v-bind="$attrs"
                     @change="handleEmits('change')"/>
    <el-radio-group v-if="inputType === 'radio'" v-model="inputValue" @change="handleEmits('change')" v-bind="$attrs">
      <el-radio v-for="item in options" :key="item.value" :value="item.value" :disabled="item.disabled">
        {{ item.label }}
      </el-radio>
    </el-radio-group>
    <el-checkbox-group v-if="inputType === 'checkbox'" v-model="inputValue" @change="handleEmits('change')"
                       v-bind="$attrs">
      <el-checkbox v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                   :disabled="item.disabled"/>
    </el-checkbox-group>
  </div>
</template>

<style scoped>
:deep(.el-input__wrapper), :deep(.el-textarea__inner), :deep(.el-select__wrapper) {
  border-radius: 0;
}
</style>